import {EventEmitter, Injectable} from '@angular/core';
import {LocalStorageService} from './local-storage.service';
import {MainService} from '../main-module/services/main.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {Router} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class ReloginService {
  public isVisibleLogin = false;
  public localStoregeUserInfoChange = new EventEmitter();
  public localStoregeUserInfoKey = 'XYLOUSERINFO';

  constructor(
    private localStorage: LocalStorageService,
    private mainService: MainService,
    private message: NzMessageService,
    private router: Router
  ) { }

  public showLoginModal(): void {
    this.isVisibleLogin = true;
  }

  public hideLoginModal(): void {
    this.isVisibleLogin = false;
  }

  public logOut(): void {
    this.setLocalStoregeInfo('', '');
    this.router.navigateByUrl('/main/home');
  }

  public doLogin(userInfo, success = (res) => {}, failed = (err) => {}): void {
    this.mainService.login(userInfo, (res) => {
      const content = res.content;
      this.setLocalStoregeInfo(content.token, content.data);
      if (res.message) { this.message.create('success', res.message); }
      this.isVisibleLogin = false;
      success(content);
    }, (err) => {
      this.setLocalStoregeInfo('', '');
      failed(err);
    });
  }

  public setLocalStoregeInfo(token: string, userInfo: string): void {
    this.localStorage.set($_xyloToken, token);
    this.localStorage.set(this.localStoregeUserInfoKey, JSON.stringify(userInfo));
    this.localStoregeUserInfoChange.emit({ userInfo });
  }
}
